﻿using ServiceStack;
using System.ServiceModel;

await Start();
//new System.Collections.Concurrent.BlockingCollection<int>(1).GetConsumingEnumerable();
//System.Threading.Channels.Channel.CreateBounded<int>(1).Reader.ReadAsync()

static async Task Start()
{
    var serviceProvider = RegisterService();
    var log = serviceProvider.GetRequiredService<ILogger<Program>>();
    try
    {
        await LoadModulesTest();
        // await VibratingSensorTest(serviceProvider);
    }
    catch (Exception e)
    {
        log.LogError(e, "应用异常");
    }
}

static async Task Other(IServiceProvider serviceProvider)
{
        UnionTest();
    await ModbusMasterTest(serviceProvider);
    await ModbusServiceTest(serviceProvider);
    await GetAbsolute();
    SkiaSharpTest();
    // ISAPI
    await QueryChannels();
    // ISAPI
    await QueryDailyDistribution();
    await GetDingDingToken();
    await SignalRClientTest();
    await OpcUaClientTest(serviceProvider);
    //取id为94的仓库地址
    var id = 94;
    var url = await GetGitProjectById(id);
    Console.WriteLine("id为{0}的仓库网址为{1}", id, url);
    GetLDAPUser();
    //模块测试，调用Grpc
    await LoadModulesTest();
    await DmDataEfSelect(serviceProvider);
    DmDataSelect(serviceProvider);
    await SimulateBalluff();
    CancellationTokenTest();
    await SoapClientTest();
    await ExportGitBranch(serviceProvider);
}
static IServiceProvider RegisterService()
{
    var serviceCollection = new ServiceCollection();
    IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    serviceCollection.AddSingleton(configuration);
    serviceCollection.AddSerilog(config => config.ReadFrom.Configuration(configuration));
    serviceCollection.AddLogging();
    serviceCollection.RegisterDameng();
    serviceCollection.RegisterModbusService();
    return serviceCollection.BuildServiceProvider();
}

static async Task SoapClientTest()
{
    var binding = new BasicHttpBinding();
    var endpoint = new EndpointAddress(@"http://localhost:5217/StudentService.asmx");
    var factory = new ChannelFactory<ServiceReference1.IContract>(binding, endpoint);
    var callClient = factory.CreateChannel();
    var requestBody = new ServiceReference1.GetRequestBody("传入的参数");
    var request = new ServiceReference1.GetRequest(requestBody);
    var response = await callClient.GetAsync(request);
    var result = response.Body.GetResult;
}


static void CancellationTokenTest()
{
    var cancelSource = new CancellationTokenSource();

    CancellationChangeToken GetToken()
    {
        return new CancellationChangeToken(cancelSource.Token);
    }

    void Handler()
    {
        Console.WriteLine("触发变化");
        var previousSource = Interlocked.Exchange(ref cancelSource, new CancellationTokenSource());
        previousSource.CancelAfter(5000);
    }
    //会立即执行GetToken
    ChangeToken.OnChange(GetToken, Handler);
    //又会执行一次GetToken
    cancelSource.Cancel();
}
